<template>
    <el-row class="organization-detail">
        <line-head-form class="head" :title="title" :type="types" />
        <el-form class="o-form" label-position="right" label-width="130px" :model="form" :rules="rules" ref="form">
            <el-form-item label="真实姓名:" prop="perName">
                <el-input v-model="form.perName" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            <el-form-item prop="perPhone" label="手机:">
                <!-- <div slot="label" class="tow-four">
                手<span>机：</span>
            </div> -->
                <el-input v-model="form.perPhone" placeholder="请输入登录手机号"></el-input>
            </el-form-item>
            <el-form-item label="合作状态:">
                <el-radio :label="0" v-model="form.status">试用期</el-radio>
                <el-radio :label="1" v-model="form.status">合约期</el-radio>
                <el-radio :label="2" v-model="form.status">终止</el-radio>
            </el-form-item>
            <el-form-item label="账号有效期:">
                <el-date-picker v-model="userTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="可免费新增账号:" prop="freeAccount">
                <el-col :span="6">
                    <el-input v-model="form.freeAccount"></el-input>
                </el-col>
                <em class="free-num">个</em>
            </el-form-item>
            <el-form-item label="合作类型:" class="required">
                <el-tooltip class="item" effect="light" content="指机构本身拥有业务 课程" placement="bottom-start">
                    <!-- <el-button class="personal"> -->
                    <el-radio :label="0" v-model="form.cooperType">
                        个性化
                    </el-radio>
                    <!-- </el-button> -->
                </el-tooltip>
                <el-radio :label="1" v-model="form.cooperType">标准</el-radio>
            </el-form-item>
            <el-form-item label="角色权限:" prop="roles">
                <el-checkbox-group v-model="form.roles">
                    <el-checkbox v-for="item in roleList" :label="item.id" :key="item.id">{{item.roleName}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="功能控制:" prop="opreaTypes">
                <el-checkbox-group v-model="form.opreaTypes">
                    <el-checkbox :label="1">课件</el-checkbox>
                    <el-checkbox :label="2">讲义</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="科目:" prop="checkedSubject">
                <el-checkbox-group v-model="form.checkedSubject" class="role-cont t-flex">
                    <el-checkbox :label="item.id" v-for="item in condition.subjectList" :key="item.id">{{item.name}}</el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="年级:" prop="checkedSubject">
                <ul>
                    <li v-for="(gradesList,index) in gradesBySubject" :key="index">
                        <h4>{{gradesList.subjectName}}</h4>
                        <div class="grade">
                            <el-checkbox label="" :key="0" v-model="gradesList.checkAll" :indeterminate="gradesList.isIndeterminate" @change="handleCheckAllChange(gradesList)">全部</el-checkbox>
                            <el-checkbox-group v-model="gradesList.sectionId" @change="handleCheckedGraderChange(gradesList)">

                                <el-checkbox :label="item.id" v-for="item in gradesList.list" :key="item.id">{{item.name}}</el-checkbox>
                            </el-checkbox-group>
                        </div>
                    </li>
                </ul>
            </el-form-item>
            <div class="opt-btn">
                <el-button :disabled="addDisabled" class="height-btn" @click="saveForm">确定</el-button>
                <el-button class="light-btn" @click="$router.go(-1)">取消</el-button>
            </div>

        </el-form>
    </el-row>
</template>
<script>
import LineHeadForm from '../../common/LineHeadForm'
import FileUpload from '../../common/FileUpload'
import io from '../../../lib/io'
import util from "../../../lib/util"
import { mapState, mapActions } from 'vuex'
export default {
    components: {
        LineHeadForm,
        FileUpload
    },
    data() {
        const validatePerName = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入您的真实姓名'));
            } else if (value.length > 40) {
                callback(new Error('输入超过最大限度40字'));
            } else {
                callback();
            }
        };
        const validatePhoneNo = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入个人手机号'));
            } else if (!(/^1[3456789]\d{9}$/.test(value))) {
                callback(new Error('手机号码有误，请重填'));
            } else {
                callback();
            }
        };
        const validateFreeAccount = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请输入免费添加账号数'));
            } else if (!(/^[0-9]*$/.test(value))) {
                callback(new Error('请输入数字'));
            } else {
                callback();
            }
        };
        return {
            addDisabled: false,
            title: "新建个人合作",
            types: 'add',
            type: this.$route.params.type,
            id: this.$route.query.id,
            userTime: [],
            roleList: [],
            gradesBySubject: [],
            form: {
                cooperType: '',
                perName: '',
                perPhone: '',
                status: '',
                effictTime: '',
                freeAccount: '',
                userTimeStart: '',
                userTimeEnd: '',
                roles: [],
                opreaTypes: [],
                checkedSubject: [],
                subjectSectionList: []
            },
            rules: {
                perName: [
                    { validator: validatePerName, trigger: 'blur' }
                ],
                perPhone: [
                    { validator: validatePhoneNo, trigger: 'blur' }
                ],
                freeAccount: [
                    { validator: validateFreeAccount, trigger: 'blur' }
                ],
                roles: [
                    { required: true, message: '请选择角色权限', trigger: 'change', }
                ],
                opreaTypes: [
                    { required: true, message: '请选择功能控制', trigger: 'change', }
                ]
            }
        }
    },
    created() {
        this.findSubjectsData({ pageIndex: 1, pageSize: 1000000, })
        this.resetForm()
        this.authRoleListForOrgan()
        if (this.type && this.id) {
            this.title = "编辑个人合作"
            this.types = 'edit'
            this.getAuthOrganDetail()
        }
    },
    computed: {
        ...mapState(['condition']),
    },
    watch:{
        'form.checkedSubject'(val){
            if (val&&val.length != 0) {
                this.findBaseSectionBySubject()
            } else {
                this.gradesBySubject = []
            }
        }
    },
    methods: {
        ...mapActions(['findSubjectsData']),
        // 全选
        handleCheckAllChange(row) {
            let allList = []
            row.list.map((item) => {
                allList.push(item.id)
            })
            row.sectionId = row.checkAll ? allList : [];
            row.isIndeterminate = false
        },
        // 全选
        handleCheckedGraderChange(row) {
            let checkedCount = row.sectionId.length;
            row.checkAll = checkedCount === row.list.length;
            row.isIndeterminate = checkedCount > 0 && checkedCount < row.list.length;
        },
        // 角色接口
        authRoleListForOrgan() {
            let param = {}
            io.post(io.authRoleListForOrgan, param, (ret) => {
                this.roleList = ret
            })
        },
        // 通过科目查找年级
        findBaseSectionBySubject(subjectSectionList) {
            let param = {
                subjectId: subjectSectionList || this.form.checkedSubject.join(',')
            }
            io.post(io.findBaseSectionBySubject, param, (ret) => {
                try {
                    ret.map(item => {
                        let sectionId = []
                        let nullData = 0
                        item.checkAll = false
                        item.isIndeterminate = true
                        if (this.form.subjectSectionList&&this.form.subjectSectionList.length >= 1) {
                            this.form.subjectSectionList.map((ite) => {
                                if (item.subjectId == ite.subjectId) {
                                    item.sectionId = ite.sectionId
                                }else {
                                    nullData++
                                    if (nullData ===this.form.subjectSectionList.length) {
                                        item.sectionId = []
                                    }
                                }
                            })
                        } else {
                            item.sectionId = []
                        }
                    })
                } catch (err) {
                    console.log(err)
                }
                this.gradesBySubject = ret
            })
        },
        resetForm() {
            this.form = {
                perName: '',
                perPhone: '',
                status: '',
                effictTime: '',
                freeAccount: '',
                userTimeStart: '',
                userTimeEnd: '',
                cooperType: '',
                roles: [],
                opreaTypes: [],
                checkedSubject: []
            }
            this.userTime = []
        },
        // 角色接口
        authRoleListForOrgan() {
            let param = {}
            io.post(io.authRoleListForOrgan, param, (ret) => {
                this.roleList = ret
            })
        },
        getAuthOrganDetail() {
            let param = {
                id: this.id
            }
            io.post(io.getAuthOrganDetail, param, (ret) => {
                ret.checkedSubject = []
                this.form = ret
                ret.subSec.length&&ret.subSec.map((item,i)=>{
                    this.form.checkedSubject.push(item.subjectId)
                })
                this.form.subjectSectionList=ret.subSec
                let userTime = []
                userTime.push(ret.userTimeStart)
                userTime.push(ret.userTimeEnd)
                this.userTime = userTime
            })
        },
        saveForm() {
            this.addDisabled = true
            setTimeout(() => {
                this.addDisabled = false
            }, 2000)
            this.$refs.form.validate((valid) => {
                if (valid) {
                    let data = Object.assign({}, this.form)
                    let authSubjectSectionList = []
                    data.checkedSubject.map((j) => {
                        this.gradesBySubject.map((val) => {
                            if (j === val.subjectId) {
                                authSubjectSectionList.push({ subjectId: val.subjectId, sectionId: val.sectionId })
                            }
                        })
                    })
                    data.authSubjectSectionList = authSubjectSectionList
                    let param = { ...this.form }
                    param.roles = param.roles.join(',')
                    param.opreaTypes = param.opreaTypes.join(',')
                    param.subSec =JSON.stringify(data.authSubjectSectionList) 
                    if (this.userTime) {
                        param.userTimeStart = util.formatDate(this.userTime[0]) + ' 00:00:00'
                        param.userTimeEnd = util.formatDate(this.userTime[1]) + ' 23:59:59'
                    } else {
                        param.userTimeStart = null
                        param.userTimeEnd = null
                    }
                    if (param.status === '') {
                        this.$message("请选择合作状态")
                        return false
                    }
                    if (!param.userTimeStart || !param.userTimeStart) {
                        this.$message("请选择账号有效期")
                        return false
                    }
                    if (param.cooperType === '') {
                        this.$message("请选择合作类型")
                        return false
                    }
                    if (this.form.checkedSubject.length <= 0) {
                        this.$message("请选择科目")
                        return false
                    }
                    let isEmpty=false
                    for (var i = 0; i < data.authSubjectSectionList.length; i++) {
                        console.log(!data.authSubjectSectionList[i].sectionId.length)
                        if (!data.authSubjectSectionList[i].sectionId.length) {
                            this.$message("你有科目未选年级,请选择")
                            isEmpty=true
                            break
                        }
                    }
                    if(isEmpty){
                        return
                    }
                    if (!(this.type && this.id)) {
                        io.post(io.addAuthOrganPerson, param, (ret) => {
                            this.$message({
                                type: 'success',
                                message: '添加成功'
                            })
                            this.$router.push('/main/system/personal/list')
                        })
                    } else {
                        param.id = this.id
                        io.post(io.updateAuthOrganPerson, param, (ret) => {
                            this.$message({
                                type: 'success',
                                message: '修改成功'
                            })
                            this.$router.push('/main/system/personal/list')
                        })
                    }
                } else {
                    this.$message('还有必填项未填，请先填写')
                    return
                }
            })
        }
    }
}
</script>
<style lang="stylus" scoped>
.organization-detail
    .o-form
        padding 0 200px
        margin auto
        margin-top 50px
    .head
      margin-top 10px
    .free-num
        margin-left 10px
        font-style normal
    .personal
        border 0
        // color #606266
        &:hover
            background transparent
        .el-radio
            color:#666
            font-family: "Microsoft YaHei",Arial,Helvetica,sans-serif,"宋体";
    .opt-btn
        text-align center
        margin-top 37px
        padding-bottom 49px
        .el-button+.el-button{
            margin-left 26px
        }
        
</style>
<style lang="stylus">
   .organization-detail
        .o-form
            .el-form-item__label:before
                content: "*";
                color: #f56c6c;
                margin-right: 4px;
            
  


</style>


